﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using SiteParser.Core.Logging;
using SiteParser.Core.Configuration;

namespace SiteParser.Core.Utilites
{
	public static class ResponseCacheManager
	{
		private static string cachePath = GetCachePath();

		public static void CacheResponse(string url, HttpWebResponse response) {
			try {
				Logger.Info(string.Format("Caching url '{0}'", url));

				if (!Directory.Exists(cachePath)) {
					Directory.CreateDirectory(cachePath);
				}

				string cacheFilePath = GetCacheFilePath(url);

				using (FileStream fStream = new FileStream(cacheFilePath, FileMode.Create)) {
					using (Stream responseStream = response.GetResponseStream()) {
						int bufferSize = 100000;

						byte[] buffer = new byte[bufferSize];
						int byteRead = 0;

						while ((byteRead = responseStream.Read(buffer, 0, bufferSize)) > 0) {
							fStream.Write(buffer, 0, byteRead);
						}	
					}
				}
			}
			catch (Exception exc) {
				Logger.Info(string.Format("Unable to cache the response. {0}", exc));
			}

			Logger.Info(string.Format("Url '{0}' is cached successfully.", url));
		}

		public static Stream GetCachedResponseStream(string url) {
			try {
				if (IsCached(url)) {
					return new FileStream(GetCacheFilePath(url), FileMode.Open);
				}
				else {
					Logger.Info(string.Format("Cache doesnt contan a response for '{0}'", url));
				}
			}
			catch (Exception exc) {
				Logger.Warning(string.Format("Unable to get respone from cache. {0}", exc));
			}

			return null;
		}

		public static bool IsCached(string url) {
			return !string.IsNullOrEmpty(url) && File.Exists(GetCacheFilePath(url));
		}

		private static string GetCacheFilePath(string url) {
			return Path.Combine(cachePath, string.Format("{0}.cache", url.GetHashCode()));
		}

		private static string GetCachePath() {
			string path = ParserConfigSection.Instance.CacheConfig.CacheFolderPath;

			if (!Path.IsPathRooted(path)) {
				path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, path);
			}

			return path;
		}
	}
}
